﻿using System;
using System.Collections.Generic;
using System.Linq;
using CSP.Common.Web;
using CSP.Model.CSP;
using CSP.Model.CSPEnum;
using CSP.Bll;
using CSP.Common.Tools;
using CSP.Bll.DTO.ServiceInfo;

namespace CSP.Web.Service
{
    public partial class Search : CSPMainPageBase
    {
        private SortType _sortType = SortType.Default;

        private List<ContactWay> _contactWays = new List<ContactWay>();

        private string _contactWaysJson = "";

        protected string ContactWaysJson
        {
            get { return _contactWaysJson; }
        }

        private const string SORTTYPE = "SortType";

        private SortType CurrentSortType
        {
            get
            {
                if (ViewState[SORTTYPE] == null)
                {
                    ViewState[SORTTYPE] = SortType.Default;
                }
                return (SortType)ViewState[SORTTYPE];
            }
            set
            {
                ViewState[SORTTYPE] = value;
            }
        }

        private const string SORTORDERCOUNTKEY = "SortOrderCountKey";

        /// <summary>
        /// Asc true,Desc false ,订单数量排序方式
        /// </summary>
        protected bool OrderCountAscOrDesc
        {
            get
            {
                if (ViewState[SORTORDERCOUNTKEY] == null)
                {
                    ViewState[SORTORDERCOUNTKEY] = true;
                }
                return (bool)ViewState[SORTORDERCOUNTKEY];
            }
            set
            {
                ViewState[SORTORDERCOUNTKEY] = value;
            }
        }

        private const string SORTSERVICECREDITKEY = "SortServiceCreditKey";

        /// <summary>
        /// Asc true,Desc false ,服务信誉排序方式
        /// </summary>
        protected bool ServiceCreditAscOrDesc
        {
            get
            {
                if (ViewState[SORTSERVICECREDITKEY] == null)
                {
                    ViewState[SORTSERVICECREDITKEY] = true;
                }
                return (bool)ViewState[SORTSERVICECREDITKEY];
            }
            set
            {
                ViewState[SORTSERVICECREDITKEY] = value;
            }
        }

        private const string SORTPRICEKEY = "SortPriceKey";

        /// <summary>
        /// Asc true,Desc false ,价格排序方式
        /// </summary>
        protected bool PriceAscOrDesc
        {
            get
            {
                if (ViewState[SORTPRICEKEY] == null)
                {
                    ViewState[SORTPRICEKEY] = false;
                }
                return (bool)ViewState[SORTPRICEKEY];
            }
            set
            {
                ViewState[SORTPRICEKEY] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitPage();
            }
        }

        /// <summary>
        /// 初始化页面
        /// </summary>
        private void InitPage()
        {
            //List<int> ids = GetServiceIds();
            SetPagerParm(0, 20, 0);
            List<SearchServiceList> searchServiceList = GetServiceList();
            SetPagerParm(0, 20, U_ServicePager.ItemCount);
            //List<SearchServiceList> searchServiceList = GetSearchServiceListByIds(ids);//GetDataByIdsDefault(ids, 0, U_ServicePager.PageSize);

            //获取联系方式
            //List<string> userNames = searchServiceList.Select(s => s.UserName).Distinct().ToList();
            //_contactWays = FindContactWayByUsers(userNames).ToList();

            _contactWaysJson = ContactWayByJson(_contactWays);
            BindSearchInfoUI(searchServiceList);


        }

        private string ContactWayByJson(List<ContactWay> contactWays)
        {
            if (contactWays.Count == 0)
            {
                return "";
            }
            List<ContactWayUI> contactWayUI = new List<ContactWayUI>();

            for (int i = 0; i < contactWays.Count; i++)
            {
                contactWayUI.Add(new ContactWayUI { Address = contactWays[i].address, Type = contactWays[i].type, UserName = contactWays[i].username });
            }
            return CommonTool.SerializeObject(contactWayUI);
        }

        /// <summary>
        /// 绑定service列表数据
        /// </summary>
        /// <param name="searchServiceList"></param>
        private void BindSearchInfoUI(List<SearchServiceList> searchServiceList)
        {
            this.R_ServiceInfo.DataSource = searchServiceList;
            this.R_ServiceInfo.DataBind();
            this.S_TotalCount.InnerHtml = U_ServicePager.ItemCount.ToString();

        }

        private List<SearchServiceList> GetSearchServiceListByIdsDefault(List<int> ids, int pageIndex, int pageSize)
        {
            List<SearchServiceList> result;
            using (var serviceInfoBll = CSPBllFactory.GetInstance().GetServiceInfoBll())
            {
                result = serviceInfoBll.GetDataByIdsDefault(ids, pageIndex, pageSize);
            }
            return result;
        }

        /// <summary>
        /// 默认排序
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public List<SearchServiceList> GetDataByIdsDefault(List<int> ids, int pageIndex, int pageSize)
        {
            List<SearchServiceList> result;
            using (var serviceInfoBll = CSPBllFactory.GetInstance().GetServiceInfoBll())
            {
                result = serviceInfoBll.GetDataByIdsDefault(ids, pageIndex, pageSize);
            }
            return result;
        }

        /// <summary>
        /// 排序按照订单数量(人气)排序
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="isSortASC"></param>
        /// <returns></returns>
        private List<SearchServiceList> GetSearchServiceListByIdsOrderByOrderCount(List<int> ids, int pageIndex, int pageSize, bool isSortASC)
        {
            List<SearchServiceList> result;
            using (var serviceInfoBll = CSPBllFactory.GetInstance().GetServiceInfoBll())
            {
                result = serviceInfoBll.GetDataByIdsOrderByOrderCount(ids, pageIndex, pageSize, isSortASC);
            }
            return result;
        }

        /// <summary>
        /// 排序按照服务信誉
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="isSortASC"></param>
        /// <returns></returns>
        private List<SearchServiceList> GetDataByIdsOrderByServiceCredit(List<int> ids, int pageIndex, int pageSize, bool isSortASC)
        {
            List<SearchServiceList> result;
            using (var serviceInfoBll = CSPBllFactory.GetInstance().GetServiceInfoBll())
            {
                result = serviceInfoBll.GetDataByIdsOrderByServiceCredit(ids, pageIndex, pageSize, isSortASC);
            }
            return result;
        }

        /// <summary>
        /// 排序按照价格 排序
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="isSortASC"></param>
        /// <returns></returns>
        public List<SearchServiceList> GetDataByIdsOrderByPrice(List<int> ids, int pageIndex, int pageSize, bool isSortASC)
        {
            List<SearchServiceList> result;
            using (var serviceInfoBll = CSPBllFactory.GetInstance().GetServiceInfoBll())
            {
                result = serviceInfoBll.GetDataByIdsOrderByPrice(ids, pageIndex, pageSize, isSortASC);
            }
            return result;
        }

        protected void U_ServicePager_IndexChange(object sender, EventArgs e)
        {
            List<SearchServiceList> searchServiceList = GetServiceList();

            //if(ids.Count==0)
            //{
            //    searchServiceList=GetSearchServiceListByIds(ids);
            //}
            //else if (CurrentSortType == SortType.Default)
            //{
            //    searchServiceList = GetDataByIdsDefault(ids, U_ServicePager.PageIndex, U_ServicePager.PageSize);
            //}
            //else if (CurrentSortType == SortType.OrderCount)
            //{
            //    searchServiceList = GetSearchServiceListByIdsOrderByOrderCount(ids, U_ServicePager.PageIndex, U_ServicePager.PageSize, OrderCountAscOrDesc);
            //}
            //else if (CurrentSortType == SortType.ServiceCredit)
            //{
            //    searchServiceList = GetDataByIdsOrderByServiceCredit(ids, U_ServicePager.PageIndex, U_ServicePager.PageSize, ServiceCreditAscOrDesc);
            //}
            //else if (CurrentSortType == SortType.Price)
            //{
            //    searchServiceList = GetDataByIdsOrderByPrice(ids, U_ServicePager.PageIndex, U_ServicePager.PageSize, PriceAscOrDesc);
            //}
            //获取联系方式
            List<string> userNames = searchServiceList.Select(s => s.UserName).Distinct().ToList();
            _contactWays = FindContactWayByUsers(userNames).ToList();
            _contactWaysJson = ContactWayByJson(_contactWays);

            BindSearchInfoUI(searchServiceList);
        }

        /// <summary>
        /// 人气排序根据订单数量
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void LB_OrderCount_Click(object sender, EventArgs e)
        {
            List<SearchServiceList> searchServiceList = GetServiceList();
            SetPagerParm(0, 20, searchServiceList.Count);
            OrderCountAscOrDesc = !OrderCountAscOrDesc;
            CurrentSortType = SortType.OrderCount;
            //List<SearchServiceList> searchServiceList = null;
            //if (ids.Count == 0)
            //{
            //    searchServiceList = GetSearchServiceListByIds(ids);
            //}
            //else 
            //{
            //    searchServiceList = GetSearchServiceListByIdsOrderByOrderCount(ids, 0, U_ServicePager.PageSize, OrderCountAscOrDesc);
            //}

            //获取联系方式
            List<string> userNames = searchServiceList.Select(s => s.UserName).Distinct().ToList();
            _contactWays = FindContactWayByUsers(userNames).ToList();
            _contactWaysJson = ContactWayByJson(_contactWays);

            BindSearchInfoUI(searchServiceList);
        }

        /// <summary>
        /// 根据服务信誉排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void LB_ServiceCredit_Click(object sender, EventArgs e)
        {
            List<SearchServiceList> searchServiceList = GetServiceList();
            SetPagerParm(0, 20, searchServiceList.Count);
            ServiceCreditAscOrDesc = !ServiceCreditAscOrDesc;
            CurrentSortType = SortType.ServiceCredit;
            //List<SearchServiceList> searchServiceList = null;

            //if (ids.Count == 0)
            //{
            //    searchServiceList = GetSearchServiceListByIds(ids);
            //}
            //else
            //{
            //    searchServiceList = GetDataByIdsOrderByServiceCredit(ids, 0, U_ServicePager.PageSize, ServiceCreditAscOrDesc);
            //}

            //获取联系方式
            List<string> userNames = searchServiceList.Select(s => s.UserName).Distinct().ToList();
            _contactWays = FindContactWayByUsers(userNames).ToList();
            _contactWaysJson = ContactWayByJson(_contactWays);

            BindSearchInfoUI(searchServiceList);
        }

        /// <summary>
        /// 根据价格排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void LB_Price_Click(object sender, EventArgs e)
        {
            List<SearchServiceList> searchServiceList = GetServiceList();
            SetPagerParm(0, 20, searchServiceList.Count);
            PriceAscOrDesc = !PriceAscOrDesc;
            CurrentSortType = SortType.Price;
            //List<SearchServiceList> searchServiceList = null;

            //if (ids.Count == 0)
            //{
            //    searchServiceList = GetSearchServiceListByIds(ids);
            //}
            //else
            //{
            //    searchServiceList = GetDataByIdsOrderByPrice(ids, 0, U_ServicePager.PageSize, PriceAscOrDesc);
            //}

            //获取联系方式
            List<string> userNames = searchServiceList.Select(s => s.UserName).Distinct().ToList();
            _contactWays = FindContactWayByUsers(userNames).ToList();
            _contactWaysJson = ContactWayByJson(_contactWays);

            BindSearchInfoUI(searchServiceList);
        }

        /// <summary>
        /// 默认排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void LB_Default_Click(object sender, EventArgs e)
        {

            List<SearchServiceList> searchServiceList = GetServiceList();
            SetPagerParm(0, 20, searchServiceList.Count);
            CurrentSortType = SortType.Default;
            InitSortRuls();


            //List<SearchServiceList> searchServiceList = GetSearchServiceListByIds(ids);

            //获取联系方式
            List<string> userNames = searchServiceList.Select(s => s.UserName).Distinct().ToList();
            _contactWays = FindContactWayByUsers(userNames).ToList();
            _contactWaysJson = ContactWayByJson(_contactWays);

            BindSearchInfoUI(searchServiceList);
        }

        /// <summary>
        /// 根据ids获取搜索列表
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        private List<SearchServiceList> GetSearchServiceListByIds(List<int> ids)
        {
            List<SearchServiceList> searchServiceList = null;
            if (ids.Count == 0)
            {
                this.DIV_SearchNothing.Visible = true;
                searchServiceList = GetDataByIds(RecommendType.NoDataRecommendRelated, 8).ToList();
            }
            else
            {
                searchServiceList = GetDataByIdsDefault(ids, 0, U_ServicePager.PageSize);
            }

            return searchServiceList;
        }

        /// <summary>
        /// 根据用户名获取联系方式
        /// </summary>
        /// <param name="userNames"></param>
        /// <returns></returns>
        private ICollection<ContactWay> FindContactWayByUsers(List<string> userNames)
        {
            ICollection<ContactWay> result;
            using (var contactWayBll = CSPBllFactory.GetInstance().GetContactWayBll())
            {
                result = contactWayBll.FindByUsers(userNames);
            }
            return result;
        }

        /// <summary>
        /// 获取推荐数据
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        private SearchServiceList[] GetDataByIds(RecommendType recommendType, int count)
        {

            string rawurl = Request.RawUrl;
            int lastTag = rawurl.LastIndexOf('/');
            string cacheSeed = "";
            string[] catalogs = null;

            //链接中不包含搜索参数时，并且以/结尾
            if (lastTag == rawurl.Length - 1 && rawurl.IndexOf('?') == -1)
            {
                catalogs = rawurl.Split('/');
                if (catalogs.Length >= 2)
                {
                    cacheSeed = catalogs[catalogs.Length - 2];
                }
            }
            //链接中不包含搜索参数时并且不是以/结尾
            else if (lastTag != rawurl.Length - 1 && rawurl.IndexOf('?') == -1)
            {
                if (catalogs != null && catalogs.Length >= 1)
                {
                    cacheSeed = catalogs[catalogs.Length - 1];
                }
            }
            //链接中包含了搜索参数
            else if (rawurl.IndexOf('?') != -1)
            {
                catalogs = rawurl.Substring(0, rawurl.IndexOf('?')).Split('/');
                if (catalogs.Length >= 2)
                {
                    cacheSeed = catalogs[catalogs.Length - 2];
                }
            }



            //string cacheSeed = ;

            SearchServiceList[] result;
            using (var recommendBll = CSPBllFactory.GetInstance().GetRecommendBll())
            {
                result = recommendBll.GetSearchServiceListByRecommendTypeAndCount(recommendType, count, cacheSeed);
            }
            return result;
        }

        /// <summary>
        /// 初始化排序规则
        /// </summary>
        private void InitSortRuls()
        {
            OrderCountAscOrDesc = false;
            ServiceCreditAscOrDesc = false;
            PriceAscOrDesc = false;
            CurrentSortType = SortType.Default;
        }

        /// <summary>
        /// 设置分页参数
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="itemCount"></param>
        private void SetPagerParm(int pageIndex, int pageSize, int itemCount)
        {
            this.U_ServicePager.PageSize = pageSize;
            this.U_ServicePager.PageIndex = pageIndex;
            this.U_ServicePager.ItemCount = itemCount;
        }

        /// <summary>
        /// 根据认证类型和认证状态获取 当前认证名称
        /// </summary>
        /// <param name="personalAuthentication"></param>
        /// <param name="enterpriseAuthentication"></param>
        /// <returns></returns>
        protected string GetCNNameByAuthentication(int personalAuthentication, int enterpriseAuthentication)
        {
            if ((AuthenticationStatus)enterpriseAuthentication == AuthenticationStatus.Accomplish)
            {
                return "企业认证";
            }

            if ((AuthenticationStatus)personalAuthentication == AuthenticationStatus.Accomplish)
            {
                return "个人认证";
            }

            return "未认证";
        }

        protected string GetPaymentByCode(string paymentCode)
        {
            ServiceAsset asset = GetAssetData(paymentCode);
            if (asset != null)
            {
                return asset.Name;
            }
            return paymentCode;
        }

        private ServiceAsset GetAssetData(string id)
        {
            //List<AgeGroup> result = new List<AgeGroup>();
            //return result;

            CSP.Model.CSP.ServiceAsset result;
            using (var serviceTypeBll = CSPBllFactory.GetInstance().GetServiceAssetBll())
            {
                result = serviceTypeBll.GetDataById(Int32.Parse(id));
            }
            return result;
        }

        /// <summary>
        /// 获取样式根据企业认证和个人认证 状态
        /// </summary>
        /// <param name="personalAuthentication"></param>
        /// <param name="enterpriseAuthentication"></param>
        /// <returns></returns>
        protected string GetStyleByAuthentication(int personalAuthentication, int enterpriseAuthentication)
        {
            //企业认证
            if ((AuthenticationStatus)enterpriseAuthentication == AuthenticationStatus.Accomplish)
            {
                return "i-v-enterprise";
            }

            //个人认证
            else if ((AuthenticationStatus)personalAuthentication == AuthenticationStatus.Accomplish)
            {
                return "i-v-personal";
            }
            else
            {
                return "i-v-unautherized";
            }
        }

        /// <summary>
        /// 根据真实的数量，返回现实的订单数量和评价数量
        /// </summary>
        /// <returns></returns>
        protected string GetOrderCountOrRatingCountByRealCount(int realCount)
        {
            string result = realCount.ToString();
            if (realCount == 0)
            {
                Random rd = new Random(0);
                result = (rd.Next(0, 10) % 3).ToString();
            }

            return result;
        }

        /// <summary>
        /// 根据价格类型，现价格，最低价格，最高价格，获取价格
        /// </summary>
        /// <param name="priceType"></param>
        /// <param name="price"></param>
        /// <param name="priceStart"></param>
        /// <param name="priceEnd"></param>
        /// <returns></returns>
        protected string GetPriceByPriceTypeAndPriceAndPriceStartAndPriceEnd(int priceType, decimal price, decimal priceStart, decimal priceEnd)
        {
            string result = "";
            if ((PriceType)priceType == PriceType.FixedPrice) //一口价
            {
                result = price.ToString("0.00");
            }
            else if ((PriceType)priceType == PriceType.PriceRange)//价格范围
            {
                result = priceStart.ToString("0.00") + "--" + priceEnd.ToString("0.00");
            }
            else if ((PriceType)priceType == PriceType.Negotiable)//面议
            {
                result = "面议";
            }
            return result;
        }

        protected string GetServiceCreditGradeByScore(int score)
        {
            return CommonTool.GetServiceCreditGradeByScore(score);
        }

        [Obsolete("该方法暂时废弃")]
        private List<int> GetServiceIds()
        {
            this.DIV_SearchNothing.Visible = false;
            List<int> result = U_SearchCondition.GetServiceIds();
            S_TotalCount.InnerHtml = result.Count.ToString();
            //if(result.Count==0)
            //{

            //    //S_TotalCount.InnerHtml = "0";
            //    result = this.LB_RecommendCurriculum.Text.Split(',').ToList().ConvertAll<int>(new Converter<string, int>(m => Convert.ToInt32(m)));

            //}

            return result;
        }

        /// <summary>
        /// 获取服务列表信息
        /// </summary>
        /// <returns></returns>
        private List<SearchServiceList> GetServiceList()
        {
            bool? orderCountSort = null;
            bool? serviceCreditSort = null;
            bool? priceSort = null;
            int? pageIndex = U_ServicePager.PageIndex;
            int? pageSize = U_ServicePager.PageSize;

            if (CurrentSortType == SortType.Default)
            {

            }
            else if (CurrentSortType == SortType.OrderCount)
            {
                orderCountSort = OrderCountAscOrDesc;
            }
            else if (CurrentSortType == SortType.ServiceCredit)
            {
                serviceCreditSort = ServiceCreditAscOrDesc;
            }
            else if (CurrentSortType == SortType.Price)
            {
                priceSort = PriceAscOrDesc;
            }

            this.DIV_SearchNothing.Visible = false;
            SearchServiceListResponseDTO response=U_SearchCondition.GetSearchServiceList(orderCountSort, serviceCreditSort, priceSort, pageIndex, pageSize);
            List<SearchServiceList> result = response.SearchServiceList;
            if (result == null || result.Count == 0)
            {
                this.DIV_SearchNothing.Visible = true;
                result = GetDataByIds(RecommendType.NoDataRecommendRelated, 8).ToList();
            }
            S_TotalCount.InnerHtml = response.TotalRecord.ToString();
            U_ServicePager.ItemCount = response.TotalRecord;
            //以下废弃
            //if(result.Count==0)
            //{

            //    //S_TotalCount.InnerHtml = "0";
            //    result = this.LB_RecommendCurriculum.Text.Split(',').ToList().ConvertAll<int>(new Converter<string, int>(m => Convert.ToInt32(m)));

            //}
            //List<SearchServiceList> result = new List<SearchServiceList>();
            return result;
        }

        protected string GetDefaultContactWayLink(string userName)
        {
            string result = "";
            ContactWay contactWay = _contactWays.FirstOrDefault(c => c.username == userName);
            if (contactWay == null)
            {
                return result;
            }
            //0 阿里旺旺
            if ((int)contactWay.type == 0)
            {
                result = CommonTool.GetTaoBaoContactURL(contactWay.address);
            }
            else if ((int)contactWay.type == 1)
            {
                result = CommonTool.GetQQContactURL(contactWay.address);
            }
            return result;
        }


        protected string GetDefaultContactWayImgSrc(string userName)
        {
            string result = "";
            ContactWay contactWay = _contactWays.FirstOrDefault(c => c.username == userName);
            if (contactWay == null)
            {
                return result;
            }
            //0 阿里旺旺
            if ((int)contactWay.type == 0)
            {
                result = "/Images/contact/WangWangOfLine.gif?";
            }
            else if ((int)contactWay.type == 1)
            {
                result = "/Images/contact/QQOfLine.gif?";
            }
            return result;
        }

        /// <summary>
        /// 获取页面的title 
        /// </summary>
        /// <returns></returns>
        protected string GetPageTitle()
        {
            return U_SearchCondition.SelectCNContext;
        }

        private enum SortType
        {

            /// <summary>
            /// 默认排序
            /// </summary>
            Default = 0,

            /// <summary>
            /// 订单(人气)数量排序
            /// </summary>
            OrderCount = 1,

            /// <summary>
            /// 服务信誉排序
            /// </summary>
            ServiceCredit = 2,

            /// <summary>
            /// 价格排序
            /// </summary>
            Price = 3,
        }

        private class ContactWayUI
        {
            public string Address { get; set; }

            public int Type { get; set; }

            public string UserName { get; set; }
        }
    }
}